<template>
	<view class="container">
		<view class="form-container">
			<text class="title">登录</text>

			<view class="input-group">
				<input v-model="loginForm.username" class="input" placeholder="请输入用户名" />
				<input v-model="loginForm.password" class="input" password placeholder="请输入密码" />
			</view>

			<button class="btn-primary" :disabled="loading" @tap="handleLogin">
				{{ loading ? '登录中...' : '登录' }}
			</button>

			<view class="link-text">
				<text>没有账号？</text>
				<text class="link" @tap="goToRegister">去注册</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				loginForm: {
					username: '',
					password: ''
				},
				loading: false
			}
		},
		methods: {
			async handleLogin() {
			    // 基础验证
			    if (!this.loginForm.username || !this.loginForm.password) {
			        uni.showToast({
			            title: '请输入用户名和密码',
			            icon: 'none'
			        })
			        return
			    }
			    
			    // 防止重复提交
			    if (this.loading) return;
			    
			    this.loading = true;
			    uni.showLoading({
			        title: '登录中...'
			    })
			
			    try {
			        const result = await uniCloud.callFunction({
			            name: 'login',
			            data: this.loginForm,
			        })
			        
			        uni.hideLoading(); // 确保与showLoading配对使用
			        this.loading = false;
			        
			        console.log('云函数返回结果:', JSON.stringify(result)); // 调试用
			        
			        // 修复：先检查result.result是否存在，再检查success
			        if (result && result.result) {
			            if (result.result.success) {
			                // 登录成功处理
			                uni.showToast({
			                    title: '登录成功',
			                    icon: 'success',
			                    duration: 2000
			                });
			                
			                // 修复：安全地访问data字段
			                const userData = result.result.data || {};
			                
			                // 保存登录状态到本地存储
			                uni.setStorageSync('currentUser', {
			                    uid: userData.uid || '',
			                    username: userData.username || this.loginForm.username,
			                    loginTime: Date.now()
			                });
			                
			                // 登录成功后延迟跳转
			                setTimeout(() => {
			                    uni.switchTab({
			                        url: '/pages/newsproject/mineHomePage/mineHomePage'
			                    });
			                }, 1500);
			                
			            } else {
			                // 显示云函数返回的具体错误信息
			                const errorMsg = result.result.errorMessage || '登录失败';
			                uni.showToast({
			                    title: errorMsg,
			                    icon: 'none',
			                    duration: 3000
			                });
			            }
			        } else {
			            // 处理云函数返回结果异常的情况
			            console.error('云函数返回结果异常:', result);
			            uni.showToast({
			                title: '服务器响应异常，请重试',
			                icon: 'none'
			            });
			        }
			    } catch (error) {
			        uni.hideLoading(); // 确保异常情况下也隐藏loading
			        this.loading = false;
			        console.error('调用云函数失败:', error);
			        uni.showToast({
			            title: '网络错误，请检查连接后重试',
			            icon: 'none'
			        });
			    }
			},
			goToRegister() {
				uni.redirectTo({
					url: '/pages/register/register'
				});
			}
		}
	}
</script>

<style>
	.container {
		display: flex;
		justify-content: center;
		align-items: center;
		min-height: 100vh;
		padding: 20rpx;
		background-color: #f5f5f5;
	}

	.form-container {
		background: white;
		padding: 60rpx 40rpx;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		width: 100%;
		max-width: 600rpx;
	}

	.title {
		font-size: 48rpx;
		font-weight: bold;
		text-align: center;
		margin-bottom: 60rpx;
		display: block;
		color: #333;
	}

	.input-group {
		margin-bottom: 60rpx;
	}

	.input {
		border: 2rpx solid #e0e0e0;
		border-radius: 8rpx;
		padding: 24rpx;
		margin-bottom: 40rpx;
		font-size: 32rpx;
	}

	.input:focus {
		border-color: #007AFF;
	}

	.btn-primary {
		background-color: #007AFF;
		color: white;
		border: none;
		border-radius: 8rpx;
		padding: 24rpx;
		font-size: 32rpx;
		margin-bottom: 40rpx;
	}

	.btn-primary:disabled {
		background-color: #cccccc;
		color: #666666;
	}

	.link-text {
		text-align: center;
		font-size: 28rpx;
		color: #666;
	}

	.link {
		color: #007AFF;
		margin-left: 10rpx;
	}
</style>